import Base from './base'
import $ from '../utils/tool'
const collectionName = 'user'
const app = getApp()
const db = wx.cloud.database()
const _ = db.command

const doc = {
  avatarUrl: '', // 头像
  nickName: '', // 昵称
  gender: 0, // 性别
  country: '',
  province: '',
  city: '',
  friendList: [], //好友列表
  logs: [],
  todayFocusNumber: 0, //今日专注次数
  todayFocusTime: 0, //今日专注时间
  totalFocusNumber: 0, //总专注次数
  totalFocusTime: 0 //总专注时间 
}

/**
 * 权限: 所有用户可读，仅创建者可写
 */

class UserModel extends Base {
  // 传入数据库名，构造数据库
  constructor() {
    super(collectionName)  // super指向当前对象的原型对象
  }

  // 增加一个用户的登录信息，增加createTime
  register() {
    return this.model.add({ data: { ...doc, createTime: this.date } }) // ...扩展运算符
  }

  // 通过openid获取用户信息
  getUserInfo(openid) {
    return this.model.where({ _openid: openid }).limit(1).get()
  }

  /**
   * 获取自己的用户信息，异步，同时updateUserInfo
   */
  async getOwnInfo(myUserInfo) {
    const { result: userInfo } = await $.callCloud('model_user_getInfo')
    console.log('getOwnInfo()', userInfo)
    if (userInfo === null) { 
      await this.register()
      console.log('初始化成功')
      await this.updateUserFocus(myUserInfo)
      console.log('更新用户focus信息成功') 
      await this.updateInfo(myUserInfo)
      console.log('更新成功') 
      return (await this.getOwnInfo())  // 重新执行一遍该函数，此时已经得到userinfo
    }
    await this.updateUserFocus(myUserInfo) //登录即更新我的userInfo
    getApp().globalData.openid = userInfo._openid //更新全局变量openid
    getApp().globalData.userInfo = userInfo //更新全局变量openid
    console.log(userInfo)
    return userInfo //这里返回的是promise
  }

  /**
   * 更新用户信息 (小程序端更新数据库基础库版本需>=2.9.4)
   * @param {Object} userInfo 用户信息
   */
  updateInfo({ avatarUrl, nickName, gender, country, province, city, friendList,  logs, todayFocusNumber, todayFocusTime, totalFocusNumber, totalFocusTime}) {
    console.log('调用updateInfo')
    return this.model.where({ _openid: '{openid}' }).update({ data: { avatarUrl, nickName, gender, country, province, city, friendList, logs, todayFocusNumber, todayFocusTime, totalFocusNumber, totalFocusTime } })
  }

  // 更新我的focus信息
  updateUserFocus(userInfo) {
    let logs = app.globalData.logs
    let totalFocusTime = app.globalData.totalFocusTime || 0
    let totalFocusNumber = app.globalData.totalFocusNumber || 0
    let todayFocusTime = app.globalData.todayFocusTime || 0
    let todayFocusNumber = app.globalData.todayFocusNumber || 0
    userInfo = {...userInfo , totalFocusTime, totalFocusNumber, todayFocusTime, todayFocusNumber }
    if(userInfo._id) {
      this.model.doc(userInfo._id).update({
        data: {
          logs: logs,
          totalFocusTime: totalFocusTime,
          totalFocusNumber: totalFocusNumber,
          todayFocusTime: todayFocusTime,
          todayFocusNumber: todayFocusNumber
        }
      })
    }else {
      console.log('未登录')
    }
    getApp().globalData.userInfo = userInfo // 更新全局变量
    return userInfo
  }

  // 获取好友榜
  async getFriendRank (friendList) {
    const { data: list } = await this.model.where({
      _id: _.or(...friendList, app.globalData.userInfo._id)
    }).orderBy('todayFocusTime', 'desc').limit(20).field({ // field指定需返回的字段
      avatarUrl: true,
      nickName: true,
      todayFocusTime: true
    }).get()
    let myInfo = {}
    const { data: userinfo } = await this.getUserInfo(app.globalData.openid)
    const data = userinfo[0]
    const { total: number } = await this.model.where({ todayFocusTime: this._.gte(data.todayFocusTime) }).count()
    myInfo = { ...data, number, todayFocusTime: data.todayFocusTime }
    return {  list: list.map(item => { return { ...item, grade: item.todayFocusTime } }), myInfo }
  }

  // 获取挑战榜，所有人的排行
  async getChallengeRank() {
    const { data: list } = await this.model.where({
      avatarUrl: this._.neq('')
    }).orderBy('totalFocusTime', 'desc').limit(20).field({
      avatarUrl: true,
      nickName: true,
      totalFocusTime: true
    }).get()
    let myInfo = {}
    const { data: userinfo } = await this.getUserInfo(app.globalData.openid)
    const data = userinfo[0]
    const { total: number } = await this.model.where({ totalFocusTime: this._.gte(data.totalFocusTime) }).count()
    myInfo = { ...data, number, grade: data.totalFocusTime }
    return { list: list.map(item => { return { ...item, grade: item.totalFocusTime } }), myInfo }
  }
}

export default new UserModel()
